<!--eslint-disable vue/no-unused-vars-->
<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <el-alert title="注意，只允许为第三级商品进行分类参数管理"  type="warning" show-icon></el-alert>
        <el-row>
            <el-col>
                <span>选择商品分类：</span>
                <el-cascader clearable
                    v-model="selectedKey"
                    :options="type3CateList"
                    :props="cascaderProps"
                    @change="cascaderChange">
                </el-cascader>
            </el-col>
        </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>
            <el-table :data="onlyList" border stripe>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-tag v-for="(item,index) in scope.row.attr_vals" closable :key="index" @close="handleCloseTag(index,scope.row)">{{item}}</el-tag>
                        <el-input class="input-new-tag"  v-if="scope.row.inputVisible" v-model="scope.row.inputValue"  ref="saveTagInput" size="small"
                         @keyup.enter.native="handleInputConfirm(scope.row)"  @blur="handleInputConfirm(scope.row)">
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)"></el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteAttr(scope.row.attr_id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
        <el-tab-pane label="动态属性" name="many">
            <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>
            <el-table :data="manyList" border stripe>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-tag v-for="(item,index) in scope.row.attr_vals" closable :key="index" @close="handleCloseTag(index,scope.row)">{{item}}</el-tag>
                        <el-input class="input-new-tag"  v-if="scope.row.inputVisible" v-model="scope.row.inputValue"  ref="saveTagInput" size="small"
                         @keyup.enter.native="handleInputConfirm(scope.row)"  @blur="handleInputConfirm(scope.row)">
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)"></el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteAttr(scope.row.attr_id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加的对话框 -->
    <el-dialog :title="'添加'+paramsTypeText+'参数'" :visible.sync="addDialogVisible" width="50%" @close="closeDialog('addFormRef')">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="名称" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改的对话框 -->
    <el-dialog :title="'修改'+paramsTypeText+'参数'" :visible.sync="editDialogVisible" width="50%" @close="closeDialog('editFormRef')">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="名称" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
        selectedKey:[],
        type3CateList:[],
        cascaderProps:{
            value:'cat_id',
            label:'cat_name',
            children:'children'
        },
        activeName:'only',
        onlyList:[],
        manyList:[],
        addDialogVisible:false,
        editDialogVisible:false,
        addForm:{
            attr_name:''
        },
        addFormRules:{
            attr_name:[
                { required: true, message: '请输入', trigger: 'blur' },
                {
                    min: 3,
                    max: 10,
                    message: '长度在3~10个字符之间',
                    trigger: 'blur'
                }
            ]
        },
        editForm:{},
        editFormRules:{
            attr_name:[
                { required: true, message: '请输入', trigger: 'blur' },
                {
                    min: 3,
                    max: 10,
                    message: '长度在3~10个字符之间',
                    trigger: 'blur'
                }
            ]
        }

    }
  },
  created(){
      this.getCurrentCateList()
  },
  methods: {
      async getCurrentCateList(){
          const {data:res} =await this.$http.get('categories',{params:{type:3}})
          if(res.meta.status != 200) return this.$message.error('获取数据失败')
          console.log(`${res.data}`)
          this.type3CateList = res.data;
      },
      cascaderChange() {
          this.checkAndGet()
      },
      handleClick(){
          console.log(this.activeName)
          this.checkAndGet()
      },
      async checkAndGet(){
          if(this.selectedKey.length != 3) {
              this.selectedKey = [];
              this.onlyList = [];
              this.manyList = [];
              return;
              }
          //这时候，吧下面的数据获取出来
          console.log(this.selectedKey);
          const {data:res} =await this.$http.get(`categories/${this.getCateId}/attributes`,{params:{sel:this.activeName}})
          if(res.meta.status != 200) return this.$message.error('获取该分类参数失败');
          console.log(`获取到的属性数据---------------------`);
          console.log(res.data)
          res.data.forEach(item =>{
              item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];//避免应为是空字符串造成数组里面会有一个空串
              item.inputValue = '';
              item.inputVisible = false;
          })
          if(this.activeName == 'only') this.onlyList = res.data;
          else this.manyList = res.data;
      },
      closeDialog(name){
          this.$refs[name].resetFields();
      },
      submitDialog(){
          this.$refs.addFormRef.validate(async valid=>{
              if(!valid) return;
              const {data:res} = await this.$http.post(`categories/${this.getCateId}/attributes`,{
                  attr_name:this.addForm.attr_name,
                  attr_sel:this.activeName
              });
              if(res.meta.status !=201) return this.$message.error('添加失败');;
              this.$message.success('添加成功');
              this.checkAndGet();
              this.addDialogVisible = false;
          })
      },
      submitEditDialog(){
          this.$refs.editFormRef.validate(async valid=>{
              if(!valid) return;
              const {data:res} = await this.$http.put(`categories/${this.getCateId}/attributes/${this.editForm.attr_id}`,{
                  attr_name:this.editForm.attr_name,
                  attr_sel:this.activeName
              });
              if(res.meta.status !=200) return this.$message.error('编辑失败');
              this.$message.success('编辑成功');
              this.checkAndGet();
              this.editDialogVisible = false;
          })
      },
      async showEditDialog(attrid){
          const {data:res} = await this.$http.get(`categories/${this.getCateId}/attributes/${attrid}`,{params:{
              attr_sel:this.activeName
          }})
          if(res.meta.status != 200) this.$message.error('属性名称获取失败')
          else{
              console.log(res);
              this.editForm = res.data;
          }
          this.editDialogVisible = true;
      },
      deleteAttr(attrid){
          this.$confirm('此操作将永久删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(async () => {
            const {data:res} = await this.$http.delete(`categories/${this.getCateId}/attributes/${attrid}`);
            if(res.meta.status != 200) return thie.$message.error('删除失败')
            this.$message.success('删除成功');
            this.checkAndGet();   
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });
          
      },
      async handleInputConfirm(obj){
          if(obj.inputValue.trim().length === 0){
              //输入无效的时候
              obj.inputVisible = false;
              obj.inputValue = '';
              return;
          }
          //输入有效
          obj.attr_vals.push(obj.inputValue.trim());
          this.tagEditHttp(obj);
          obj.inputVisible = false; 
          obj.inputValue = '';
      },
      showInput(obj){
          obj.inputVisible = true;
          //文本框自动获取焦点
          //$nextTick 只有当页面上元素渲染出来之后，在执行下面的函数
          this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
       handleCloseTag(i,obj) {
          obj.attr_vals.splice(i,1);
          this.tagEditHttp(obj);
      },
      async tagEditHttp(obj){
          const {data:res} = await this.$http.put(`categories/${this.getCateId}/attributes/${obj.attr_id}`,{
                  attr_name:obj.attr_name,
                  attr_sel:obj.attr_sel,
                  attr_vals:obj.attr_vals.join(' ')
              });
          if(res.meta.status != 200) return this.$message.error('修改失败');
          this.$message.success('修改成功')
      }
  },
  computed:{
      //返回布尔值，可以控制按钮的启用否
      isBtnDisabled() {
          if(this.selectedKey.length != 3) return true;
          return false;
      },
      //获取数组中最后的数字
      getCateId(){
          if(this.selectedKey.length == 3) return this.selectedKey[this.selectedKey.length - 1];
          return null;
          
      },
      paramsTypeText(){
          if(this.activeName == 'only') return '静态';
          else return '动态';
      }
  },
  components: {

  }
}
</script>

<style lang='less' scoped>
.el-alert{
    margin-bottom: 10px;
}

.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>